package com.smartsofa.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.integer;
import android.R.string;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshExpandableListView;
import com.smartsofa.R;
import com.smartsofa.adapter.FamilyListAdapter;
import com.smartsofa.main.AddFamilyGroup;
import com.smartsofa.main.MemberHistoryActivity;
import com.smartsofa.util.MyUtils;

public class FamilyFragment extends Fragment {
	private FragmentActivity mActivity;
	private View mParent;
	
	private static ArrayList<Map<String,String>> parentData = new ArrayList<Map<String,String>>();  
    private static ArrayList<ArrayList<Map<String,String>>> childData = new ArrayList<ArrayList<Map<String,String>>>();  
    private PullToRefreshExpandableListView elistview;  

	private ProgressDialog mDialog;
    private LayoutInflater layoutInflater;
    private int familyId;
    FamilyListAdapter mAdapter;
	
	private String url;
	private Boolean flag=false;
	private String reg_msg;
	private JSONObject json;
	//定义网络连接超时判定变量
	private boolean network_timeout=false; 
	Map<integer, string> imgMap = null;
    
    public void getData(){
    	parentData.clear();
    	childData.clear();

		Thread getFamilyList_thread=new Thread(new getFamilyList());
		getFamilyList_thread.start();
    }  
    
    class getFamilyList implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {			
				url=MyUtils.getUrl()+"family_familyList?userid="+MyUtils.getUSERID();
				HttpGet request = new HttpGet(url);																
				BasicHttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
			    HttpClient httpClient = new DefaultHttpClient(httpParams);
	            HttpResponse httpResponse = httpClient.execute(request);					       
		       	
		      if (httpResponse.getStatusLine().getStatusCode() == 200) {
		    	  network_timeout=true;
		          String jsonString = EntityUtils.toString(httpResponse.getEntity());
		          json = new JSONObject(jsonString);
		          flag=json.getBoolean("success");
		          reg_msg=json.getString("msg");
		          Message msg = content_handler.obtainMessage();
					if(network_timeout){
						if (flag) {				
							msg.what = 1;
							
						}else{
							msg.what = 2;			
						}
					}			
					else{
						msg.what = 3;						
					}
					content_handler.sendMessage(msg);
		         
		      }
		      }catch (Exception e) {
		        	 e.printStackTrace();
		     }
		}
    	
    }
	Handler content_handler = new Handler() {
		public void handleMessage(Message msg) {	
			mDialog.dismiss();
			switch (msg.what) {		
			case 1:	
		     	try {
					JSONArray jsonarr1=json.getJSONArray("obj");
					for(int i=0;i<jsonarr1.length();i++){
						 Map<String,String> map = new HashMap<String,String>();  
						 JSONObject jsonobj_temp=jsonarr1.getJSONArray(i).getJSONObject(0);
						 
						 map.put("familyName", jsonobj_temp.getString("familyName"));
						 map.put("signature", jsonobj_temp.getString("signature"));
						 map.put("memberNum", jsonobj_temp.getString("memberNum"));
						 map.put("familyId", jsonobj_temp.getString("familyId"));
						 map.put("adminId", jsonobj_temp.getString("adminId"));
						 map.put("createTime", jsonobj_temp.getString("createTime"));
						 map.put("familyImg", jsonobj_temp.optString("familyImg"));
			             parentData.add(map);  
					} 					
					JSONArray jsonarr2=json.getJSONArray("obj2");
					for(int i=0;i<jsonarr1.length();i++){
						ArrayList<Map<String,String>> child = new ArrayList<Map<String,String>>();  
			            for(int j=0; j<jsonarr2.getJSONArray(i).length();j++){  			            	
			                Map<String,String> map = new HashMap<String,String>(); 
			                JSONObject json_temp=jsonarr2.getJSONArray(i).getJSONObject(j);
			                map.put("familyId", json_temp.getString("familyId"));
			                map.put("memberId", json_temp.getString("memberId"));
			                map.put("userId", json_temp.getString("userId"));
			                map.put("userImg", json_temp.optString("userImg"));
			                map.put("userName", json_temp.optString("userName"));
			                child.add(map);  
			            }  
			            childData.add(child);
					}
					elistview.onRefreshComplete();
					mAdapter=new FamilyListAdapter(mActivity.getApplicationContext(), parentData, childData);
			        elistview.getRefreshableView().setAdapter(mAdapter);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		     	break;
			case 2:
				Toast.makeText(mActivity,reg_msg.toString(),Toast.LENGTH_SHORT).show();
				break;
			case 3:
				Toast.makeText(mActivity,"网络连接超时!",Toast.LENGTH_SHORT).show();
				break;
		     }
		}
	};
	
    
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view=inflater.inflate(R.layout.fragment_family, container,false);
		return view;
	}
	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mActivity = getActivity();  
	    mParent = getView();
	    layoutInflater = getActivity().getLayoutInflater();
	    //获取列表数据
    	mDialog = new ProgressDialog(mActivity);
		mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mDialog.setMessage("列表加载中，请稍候...");
		mDialog.show();
        getData();  
	    LinearLayout lay_addFamily=(LinearLayout) mActivity.findViewById(R.id.lay_addfamily);
	    lay_addFamily.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent=new Intent();
				intent.setClass(mActivity, AddFamilyGroup.class);
				startActivity(intent);
			}
		});	   
		elistview=(PullToRefreshExpandableListView) mActivity.findViewById(R.id.lv_family_member);
        elistview.setOnRefreshListener(new OnRefreshListener<ExpandableListView>() {

			@Override
			public void onRefresh(
					PullToRefreshBase<ExpandableListView> refreshView) {
				// TODO Auto-generated method stub				
			   getData(); 
			}
		}); 
        //添加长按删除事件
        elistview.getRefreshableView().setOnItemLongClickListener(new OnItemLongClickListener(){

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0,
					View arg1, final int arg2, long arg3) {
				// TODO Auto-generated method stub							
				AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
				builder.setMessage("确定要删除此家庭组?")
				       .setCancelable(false)
				       .setPositiveButton("确定", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                Thread thread=new Thread(new delete_family(Integer.valueOf(parentData.get(arg2).get("familyId")),arg2));
				                thread.start();
				            	mDialog = new ProgressDialog(mActivity);
				        		mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				        		mDialog.setMessage("处理中，请稍候...");
				        		mDialog.show();
				           }
				       })
				       .setNegativeButton("取消", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                dialog.cancel();
				           }
				       }).show();
				AlertDialog alert = builder.create();
				return false;
			}
        	
        });
        //添加点击子项事件
        elistview.getRefreshableView().setOnChildClickListener(new OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView parent, View arg1, int groupPosition,
					int childPosition, long arg4) {
				// TODO Auto-generated method stub
				String userid = childData.get(groupPosition).get(childPosition).get("userId").toString();
				Intent intent = new Intent(mActivity, MemberHistoryActivity.class);
				intent.putExtra("userID", userid);//用户ID 
				mActivity.startActivity(intent);
				return false;
			}
		});
	}
	/**
	 * 删除家庭组
	 */
	class delete_family implements Runnable{
		int familyid;
		int groupid;
		public delete_family(int familyid, int id){
			this.familyid=familyid;
			this.groupid=id;
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {			
				url=MyUtils.getUrl()+"family_deleteFamily?userid="+MyUtils.getUSERID()+"&familyid="+familyid;
				HttpGet request = new HttpGet(url);																
				BasicHttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
			    HttpClient httpClient = new DefaultHttpClient(httpParams);
	            HttpResponse httpResponse = httpClient.execute(request);					       
		       	
		      if (httpResponse.getStatusLine().getStatusCode() == 200) {
		    	  network_timeout=true;
		          String jsonString = EntityUtils.toString(httpResponse.getEntity());
		          
		          json = new JSONObject(jsonString);
		          flag=json.getBoolean("success");
		          reg_msg=json.getString("msg");
		          Message msg = delete_handler.obtainMessage();
					if(network_timeout){
						if (flag) {				
							msg.what = 1;
							
						}else{
							msg.what = 2;			
						}
					}			
					else{
						msg.what = 3;						
					}
					Bundle bundle = new Bundle();  
	                bundle.putInt("groupid", groupid); 
					msg.setData(bundle);
					delete_handler.sendMessage(msg);
		         
		      }
		      }catch (Exception e) {
		        	 e.printStackTrace();
		     }
		}
	}
	Handler delete_handler = new Handler() {
		public void handleMessage(Message msg) {	
			mDialog.dismiss();
			switch (msg.what) {		
			case 1:
				System.out.println(msg.getData().getInt("groupid"));
				parentData.remove(msg.getData().getInt("groupid"));
				mAdapter.notifyDataSetChanged();
				break;
			case 2:
				Toast.makeText(mActivity,reg_msg.toString(),Toast.LENGTH_SHORT).show();
				break;
			case 3:
				Toast.makeText(mActivity,"网络连接超时!",Toast.LENGTH_SHORT).show();
				break;
		     }
		}
	};
}
